var log4js = require('log4js');
var logger = log4js.getLogger('INVOKE');

var hfc = require('fabric-client');
var utils = require('fabric-client/lib/utils.js');
var Peer = require('fabric-client/lib/Peer.js');
var Orderer = require('fabric-client/lib/Orderer.js');
var EventHub = require('fabric-client/lib/EventHub.js');

var config = require('./config.json');
var helper = require('./helper.js');

logger.setLevel('DEBUG');

var client = new hfc();
var chain;
var eventhub;
var tx_id = null;

module.exports.init = function() {
    chain = client.newChain(config.chainName);
    chain.addOrderer(new Orderer(config.orderer.orderer_url));
    eventhub = new EventHub();
    eventhub.setPeerAddr(config.events[0].event_url);
    eventhub.connect();
    for (var i = 0; i < config.peers.length; i++) {
        chain.addPeer(new Peer(config.peers[i].peer_url));
    }
}

module.exports.make = function(id, amount, req, res) {
    hfc.newDefaultKeyValueStore({
        path: config.keyValueStore
    }).then(function(store) {
        client.setStateStore(store);
        return helper.getSubmitter(client);
    }).then(
        function(admin) {
            logger.info('Successfully obtained user to submit transaction');

            logger.info('Executing Invoke');
            tx_id = helper.getTxId();
            var nonce = utils.getNonce();
            var args = [
                "assets",
                id,
                amount
            ];
            // send proposal to endorser
            var request = {
                chaincodeId: config.chaincodeID,
                fcn: "invoke",
                args: args,
                chainId: config.channelID,
                txId: tx_id,
                nonce: nonce
            };
            return chain.sendTransactionProposal(request);
        }
    ).then(
        function(results) {
            logger.info('Successfully obtained proposal responses from endorsers');
            return helper.processProposal(tx_id, eventhub, chain, results, 'assets');
        }
    ).then(
        function(response) {
            if (response.status === 'SUCCESS') {
                logger.info('The chaincode transaction has been successfully committed, Exit..');
                res.send({ result: "true" });
            } else {
                logger.info('The chaincode transaction has been successfully committed, ' + response + 'Exit..');
                res.send({ result: "false" });
            }
        }
    ).catch(
        function(err) {
            res.send({ result: "false" });
            eventhub.disconnect();
            logger.error('Failed to invoke transaction due to error: ' + err.stack ? err.stack : err);
        }
    );

}